package com.itheima.mp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.mp.domain.po.LoginUser;
import com.itheima.mp.domain.po.SgUser;
import com.itheima.mp.mapper.SgUserMapper;
import com.itheima.mp.mapper.SysMenuMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class UserDetailServiceImpl implements UserDetailsService {

    private final SgUserMapper sgUserMapper;
    private final SysMenuMapper sysMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        LambdaQueryWrapper<SgUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SgUser::getUserName, username);
        SgUser user = sgUserMapper.selectOne(queryWrapper);
        // 判断是否为空
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或者密码错误");
        }
        //TODO 查询对应的权限信息
        List<String> list = sysMenuMapper.selectPermsByUserId(user.getId());
        // 把数据封装成UserDetails对象并返回
        return new LoginUser(user, list);
    }
}
